/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Unite.java
 *
 * Created on Sep 6, 2009, 12:30:40 AM
 */

package GUI;


import functions.Dogs;
import functions.Dogy;
import functions.OldUsers;
import functions.Users;
import java.awt.Color;
import java.awt.Component;

import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.DropMode;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.table.DefaultTableModel;
import model.Dog;
import model.User;
import stuff.LabelTableCellRenderer;
import stuff.ListTextField;
import stuff.TableButtonEditor;
import stuff.TableButtonRenderer;

/**
 *
 * @author JArik
 */
class DogTransfer
{
   
}


class UserListRenderer extends JLabel implements ListCellRenderer
{

    public UserListRenderer()
    {
        this.setOpaque(true);
    }
    @Override
    public Component getListCellRendererComponent(JList list, Object obj,
                                                  int rowCol, boolean isSelected,
                                                  boolean hasFocus) {
        if(obj instanceof User)
        {
            User user = (User)obj;
            this.setText("<html><b>"+user.getFullName() + "</b><br/> " + user.getStreet());
        }
        if(isSelected)
        {
            this.setForeground(list.getSelectionForeground());
            this.setBackground(list.getSelectionBackground());
        }else
        {
            this.setForeground(list.getForeground());
            this.setBackground(list.getBackground());
        }
        return this;
    }
}
class DogsTableButtonRenderer extends TableButtonRenderer
{
    public DogsTableButtonRenderer(String name)
    {
        super(name);
        this.createToolTip().setTipText("Перенести жывотного");
    }
    public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        if(isSelected)
            this.setBackground(table.getSelectionBackground());
        else
            this.setBackground(table.getBackground());

        if((Boolean)table.getValueAt(row, column) == false)
            this.setEnabled(false);
        else
            this.setEnabled(true);

        
        return this;
    }
}

class DogsTableButtonEditor extends TableButtonEditor
{
    private Object value;
    public DogsTableButtonEditor(String name, ActionListener actionListener)
    {
        super(name);
        this.addActionListener(actionListener);
    }
    public Object getCellEditorValue() {
        return value;
    }
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected, int row, int column)
    {
        if((Boolean)value == false)
            this.setEnabled(false);
        else
            this.setEnabled(true);
        
        this.value = value;

        
        return this;
    }
}
class DogLabelCellRenderer extends LabelTableCellRenderer
{
    public DogLabelCellRenderer()
    {
        this.setOpaque(true);
    }
    public Component getTableCellRendererComponent(JTable table, Object value,
                                               boolean isSelected, boolean hasFocus,
                                               int row, int column)
    {
        if(value instanceof Dog)
        {
            Dog dog = (Dog)value;
            this.setText(dog.getBreed()+
                    (dog.getNick() == null || dog.getNick().isEmpty() ? "":" ("+dog.getNick()+")") );
        }
        if(isSelected)
        {
            this.setForeground(table.getSelectionForeground());
            this.setBackground(table.getSelectionBackground());
        }else
        {
            this.setForeground(table.getForeground());
            this.setBackground(table.getBackground());
        }
        return this;
    }
}

public class Unite extends javax.swing.JFrame  {

    /** Creates new form Unite */
    private MainFrame mainFrame;
    private ArrayList<User> users;
    private Search search;
    private String findUserText;

    private JDialog dragDialog;
    private ListTextField activeField;
    private DefaultListModel fromUserListModel, toUserListModel;

    public Unite()
    {
        initComponents();
        findUserText = "Добавить клиента";
        findUserDogTransferField.setText("Добавить клиента");
        //dogsTable.setDragEnabled(true);
        fromUserList.setDropMode(DropMode.ON);
        boxPopup.add(boxList);
        fromUserList.setCellRenderer(new UserListRenderer());
    }
    
    public Unite(MainFrame mf, ArrayList<User> users, Search search)
    {
        mainFrame = mf;
        this.users = users;
        this.search = search;
        initComponents();


        Dogy.placeToCenter(this);
        this.setTitle("Обьеденить\\Перенести");
        
        findUserText = "Добавить клиента";
        findUniteUserField.setText(findUserText);
        findUniteUserField.setForeground(Color.gray);
        findUserDogTransferField.setText(findUserText);
        findUserDogTransferField.setForeground(Color.gray);

        fromUserListModel = new DefaultListModel();
        toUserListModel = new DefaultListModel();
        
        fromUserList.setModel(fromUserListModel);
        toUserList.setModel(toUserListModel);
        
        fromUserList.setDropMode(DropMode.ON);
        boxPopup.add(boxList);
        list.setCellRenderer(new UserListRenderer());
        fromUserList.setCellRenderer(new UserListRenderer());
        toUserList.setCellRenderer(new UserListRenderer());
        if(users != null && users.size() > 0)
        {
            mainClientField.setText(users.get(0).toString());
            streetField.setText(users.get(0).getStreet());
            fillUniteTable();
            fillDogTransfer();
        }

    }

    public void setActiveTab(int t)
    {
        uniteTabs.setSelectedIndex(t);
    }
    private void fillUniteTable()
    {
        DefaultTableModel model = (DefaultTableModel)uniteTable.getModel();
        model.setRowCount(0);
        for(int i=0; i< users.size(); i++)
        {
            model.addRow(new Object[] {users.get(i), (i== 0 ? true:false) });
        }
        uniteTable.setModel(model);
        
    }

    private void fillDogTransfer()
    {
        for(int i=0; i< users.size(); i++)
        {
            fromUserListModel.addElement(users.get(i));
            toUserListModel.addElement(users.get(i));
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        boxPopup = new javax.swing.JPopupMenu();
        boxList = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        uniteTabs = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        uniteTable = new javax.swing.JTable();
        uniteButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        mainClientField = new javax.swing.JLabel();
        streetField = new javax.swing.JLabel();
        findUniteUserField = new ListTextField()
        {
            public Object listPressed(java.awt.event.InputEvent evt)
            {
                userTransferListClicked(evt);
                return null;
            }
        };
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        fromUserList = new javax.swing.JList();
        findUserDogTransferField = new ListTextField()
        {
            public Object listPressed(java.awt.event.InputEvent evt)
            {
                dogTransferListClicked(evt);
                return null;
            }
        }
        ;
        jButton2 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        dogsTable = new javax.swing.JTable();
        fromLabel = new javax.swing.JLabel();
        fromUserLabel = new javax.swing.JLabel();
        fromLabel1 = new javax.swing.JLabel();
        toUserLabel = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        toUserList = new javax.swing.JList();

        boxPopup.setAutoscrolls(true);
        boxPopup.setMaximumSize(new java.awt.Dimension(390, 645555));

        boxList.setAutoscrolls(true);
        boxList.setMaximumSize(new java.awt.Dimension(390, 645555));
        boxList.setMinimumSize(new java.awt.Dimension(380, 120));
        boxList.setPreferredSize(new java.awt.Dimension(380, 120));

        list.setFont(new java.awt.Font("Tahoma", 0, 12));
        list.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Добавить новое" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        list.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        list.setMaximumSize(new java.awt.Dimension(390, 300));
        list.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listMouseClicked(evt);
            }
        });
        boxList.setViewportView(list);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        uniteTabs.setFont(new java.awt.Font("Tahoma", 0, 14));
        uniteTabs.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                uniteTabsMouseReleased(evt);
            }
        });

        uniteTable.setFont(new java.awt.Font("Tahoma", 0, 14));
        uniteTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Клиент", "Основной"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
            public void setValueAt(Object value, int row, int column)
            {
                if(column == 1)
                {
                    if((Boolean)value == true)
                    {
                        for(int i=0; i<uniteTable.getRowCount(); i++)
                        super.setValueAt(false, i, 1);
                        super.setValueAt(true, row, 1);
                        mainClientField.setText(super.getValueAt(row,0).toString());
                        streetField.setText(((User)super.getValueAt(row,0)).getStreet());
                    }else
                    {
                        //super.setValueAt(false, row, 1);
                        //super.setValueAt(true, 0, 1);
                        //mainClientField.setText(super.getValueAt(0,0).toString());
                        //streetField.setText(((User)super.getValueAt(0,0)).getStreet());
                    }
                }else
                super.setValueAt(value, row, column);
            }
        });
        uniteTable.setRowHeight(20);
        jScrollPane1.setViewportView(uniteTable);

        uniteButton.setFont(new java.awt.Font("Tahoma", 1, 12));
        uniteButton.setText("Обьеденить");
        uniteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uniteButtonActionPerformed(evt);
            }
        });

        closeButton.setFont(new java.awt.Font("Tahoma", 1, 12));
        closeButton.setText("Закрыть");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel1.setText("Информация об обьедененном клиенте, будет взята с:");

        mainClientField.setFont(new java.awt.Font("Tahoma", 1, 14));
        mainClientField.setText(" ");

        streetField.setFont(new java.awt.Font("Tahoma", 0, 14));
        streetField.setText(" ");

        findUniteUserField.setFont(new java.awt.Font("Tahoma", 0, 14));
        findUniteUserField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                findUniteUserFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                findUniteUserFieldFocusLost(evt);
            }
        });
        findUniteUserField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                findUniteUserFieldKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                findUniteUserFieldKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 208, Short.MAX_VALUE)
                        .addComponent(uniteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(findUniteUserField, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
                    .addComponent(mainClientField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
                    .addComponent(streetField, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(findUniteUserField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(mainClientField)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(streetField)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(uniteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        uniteTabs.addTab("Обьеденить", jPanel1);

        fromUserList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        fromUserList.setDoubleBuffered(true);
        fromUserList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fromUserListMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                fromUserListMouseReleased(evt);
            }
        });
        fromUserList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                fromUserListValueChanged(evt);
            }
        });
        fromUserList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                fromUserListKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(fromUserList);

        findUserDogTransferField.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        findUserDogTransferField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                findUserDogTransferFieldFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                findUserDogTransferFieldFocusLost(evt);
            }
        });
        findUserDogTransferField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                findUserDogTransferFieldKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                findUserDogTransferFieldKeyReleased(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 14));
        jButton2.setText("Закрыть");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jScrollPane3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));

        dogsTable.setFont(new java.awt.Font("Tahoma", 0, 14));
        dogsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Имя/Порода", "Д.Р.",">"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class,java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        dogsTable.getColumnModel().getColumn(2).setMaxWidth(25);
        dogsTable.getColumnModel().getColumn(2).setCellEditor(new DogsTableButtonEditor(">",
            new ActionListener()
            {
                public void actionPerformed(java.awt.event.ActionEvent evt)
                {
                    dogTableButtonPressed(evt);
                }
            }));
            dogsTable.getColumnModel().getColumn(2).setCellRenderer(new DogsTableButtonRenderer(">"));
            dogsTable.getColumnModel().getColumn(0).setCellRenderer(new DogLabelCellRenderer());
            dogsTable.setDoubleBuffered(true);
            dogsTable.setIntercellSpacing(new java.awt.Dimension(2, 1));
            dogsTable.setRowHeight(20);
            dogsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
            dogsTable.setShowVerticalLines(false);
            dogsTable.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    dogsTableMousePressed(evt);
                }
            });
            dogsTable.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    dogsTableMouseDragged(evt);
                }
            });
            jScrollPane3.setViewportView(dogsTable);
            dogsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

            fromLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
            fromLabel.setText("Перенести от:");

            fromUserLabel.setFont(new java.awt.Font("Tahoma", 0, 14));

            fromLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
            fromLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
            fromLabel1.setText("Перенести к:");

            toUserLabel.setFont(new java.awt.Font("Tahoma", 0, 14));
            toUserLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);

            toUserList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
            toUserList.setDoubleBuffered(true);
            toUserList.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    toUserListMouseClicked(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    toUserListMouseReleased(evt);
                }
            });
            toUserList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
                public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                    toUserListValueChanged(evt);
                }
            });
            toUserList.addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyReleased(java.awt.event.KeyEvent evt) {
                    toUserListKeyReleased(evt);
                }
            });
            jScrollPane4.setViewportView(toUserList);

            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(findUserDogTransferField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel2Layout.createSequentialGroup()
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(73, 73, 73)))
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(fromUserLabel, 0, 0, Short.MAX_VALUE)
                                .addComponent(fromLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(18, 18, 18)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(toUserLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
                                .addComponent(fromLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE))))
                    .addContainerGap())
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(findUserDogTransferField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(fromLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(fromLabel1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(fromUserLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
                        .addComponent(toUserLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                            .addComponent(jScrollPane3, 0, 0, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap())
            );

            uniteTabs.addTab("Перенести Животных", jPanel2);

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(uniteTabs, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(uniteTabs, javax.swing.GroupLayout.Alignment.TRAILING)
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

    private void uniteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uniteButtonActionPerformed
        DefaultTableModel model = (DefaultTableModel)uniteTable.getModel();
        ArrayList<Integer> toUnite = new ArrayList<Integer>();
        int mainId = -1;
        for(int i=0; i< model.getRowCount(); i++)
        {
            if((Boolean)model.getValueAt(i, 1) == false)
              toUnite.add(((User)model.getValueAt(i, 0)).getId());
            else
              mainId =  ((User)model.getValueAt(i, 0)).getId();
        }
        try
        {
          Users.uniteUsers(mainId, toUnite);
          OldUsers.uniteVisits(mainId, toUnite);
          Users.delete(toUnite);
          search.refreshSearch();
          this.dispose();
        } catch(SQLException e)
        {
            mainFrame.FormException(this, e.getMessage());
        }
    }//GEN-LAST:event_uniteButtonActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        boxPopup.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    private void findUserDogTransferFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_findUserDogTransferFieldFocusGained
        Dogy.focusGained(findUserDogTransferField, findUserText);
}//GEN-LAST:event_findUserDogTransferFieldFocusGained

    private void findUserDogTransferFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_findUserDogTransferFieldFocusLost
        Dogy.focusLost(findUserDogTransferField, findUserText);
}//GEN-LAST:event_findUserDogTransferFieldFocusLost

    private void dogsTableMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dogsTableMouseDragged
        if(dragDialog != null && dragDialog.isVisible())
        {
            dragDialog.setLocation(evt.getLocationOnScreen().x-5,
                                                 evt.getLocationOnScreen().y-5);
            return;
        }
        dragDialog = new JDialog();
        dragDialog.setUndecorated(true);
        JLabel label = new JLabel("Drag dogs");

        dragDialog.add(label);
        dragDialog.setVisible(true);
        dragDialog.setLocation(evt.getLocationOnScreen().x-5,
                                                 evt.getLocationOnScreen().y-5);
        dragDialog.addMouseListener(new MouseAdapter()
        {
            public void mouseReleased(java.awt.event.MouseEvent e)
            {
                dragDialog.dispose();
            }
        });
        dragDialog.pack();
       
    }//GEN-LAST:event_dogsTableMouseDragged

    private void dogTableButtonPressed(java.awt.event.ActionEvent evt)
    {
        Dog dog = (Dog)dogsTable.getValueAt(dogsTable.getSelectedRow(), 0);
        User user = (User)toUserList.getSelectedValue();
        try {
            Dogs.changeDog(dog.getId(),
                           user.getId(),
                           dog.getNick(),
                           dog.getBreed(),
                           dog.getBirthDate(),
                           dog.getDeathDate());
            dogsTable.getCellEditor(dogsTable.getSelectedRow(), 2).stopCellEditing();
            ((DefaultTableModel) dogsTable.getModel()).removeRow(dogsTable.getSelectedRow());
        } catch (SQLException ex) {
            mainFrame.SQLException(ex);
        }
    }
    private void fromUserListMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fromUserListMouseReleased
    
        //userList.locationToIndex(evt.getLocationOnScreen());
        //if(dragDialog != null)
        //  dragDialog.dispose();
}//GEN-LAST:event_fromUserListMouseReleased

    private void dogsTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dogsTableMousePressed
        /*dragDialog = new JDialog();
        dragDialog.setUndecorated(true);
        JLabel label = new JLabel("Drag dogs");
        
        dragDialog.add(label);
        dragDialog.setVisible(true);
        dragDialog.setDefaultCloseOperation(dragDialog.DISPOSE_ON_CLOSE);
        dragDialog.pack();*/
    }//GEN-LAST:event_dogsTableMousePressed

    private void uniteTabsMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_uniteTabsMouseReleased

        if(dragDialog != null)
          dragDialog.dispose();
}//GEN-LAST:event_uniteTabsMouseReleased

    private void listMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listMouseClicked
        
        boxPopup.setVisible(false);
        
        {
            if(activeField != null)
            {
                activeField.listPressed(evt);
                activeField.setText("");
            }
        }
}//GEN-LAST:event_listMouseClicked

    private void dogTransferListClicked(java.awt.event.InputEvent evt)
    {
        fromUserListModel.addElement(list.getSelectedValue());
        toUserListModel.addElement(list.getSelectedValue());
    }

    private void userTransferListClicked(java.awt.event.InputEvent evt)
    {
        ((DefaultTableModel)uniteTable.getModel()).addRow(
                new Object[]{
                            list.getSelectedValue(),
                            (uniteTable.getRowCount() == 0 ? true:false)
                            });
        uniteTable.setValueAt(uniteTable.getValueAt(0, 1), 0, 1);
    }
    private void findUserDogTransferFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_findUserDogTransferFieldKeyPressed
        Dogy.listScroll(list, evt);
}//GEN-LAST:event_findUserDogTransferFieldKeyPressed

    private void findUserDogTransferFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_findUserDogTransferFieldKeyReleased

        showUserList(findUserDogTransferField, evt);
}//GEN-LAST:event_findUserDogTransferFieldKeyReleased


    private void showUserList(JTextField field, java.awt.event.KeyEvent evt)
    {
        activeField = (ListTextField) field;
        if( evt != null && evt.getKeyCode() == KeyEvent.VK_ENTER) {
            boxPopup.setVisible(false);

            if(!activeField.getText().equals("") && list.getSelectedIndex() >=0)
               listMouseClicked(null);

            activeField.requestFocus();
        } else if(evt != null && evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            boxPopup.setVisible(false);
        }else
        if(activeField.getText().length() >= 2 && (!evt.isActionKey() || evt == null))
        try
        {
            Users searchUsers = new Users();
            searchUsers.groupByName();
            searchUsers.searchByName(activeField.getText());
            ArrayList<User> usersArray = searchUsers.startSearch();

            list.ensureIndexIsVisible(0);
            list.setListData(usersArray.toArray());


            boxPopup.setLocation(activeField.getLocationOnScreen().x,
                        activeField.getLocationOnScreen().y + activeField.getHeight());

            list.repaint();
            boxPopup.repaint();

            if(usersArray.size() > 0)
                  boxPopup.setVisible(true);
            else
                  boxPopup.setVisible(false);

            if( evt != null && evt.getKeyCode() == KeyEvent.VK_ENTER) {
            boxPopup.setVisible(false);

            if(!activeField.getText().equals("") && list.getSelectedIndex() >=0)
               listMouseClicked(null);

            activeField.requestFocus();

            } else if(evt != null && evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
                boxPopup.setVisible(false);
            }
        }catch(SQLException ex)
        {
            ex.printStackTrace();
            mainFrame.SQLException(ex);
        }

    }
    private void fromUserListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fromUserListMouseClicked
        if(evt == null || evt.getClickCount() >= 2)
        {
            User user = (User)fromUserList.getSelectedValue();
            fillDogsTable(user);
        }
}//GEN-LAST:event_fromUserListMouseClicked

    private void fromUserListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fromUserListKeyReleased
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            fromUserListMouseClicked(null);
}//GEN-LAST:event_fromUserListKeyReleased

    private void fromUserListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_fromUserListValueChanged
         User user = (User)fromUserList.getSelectedValue();
         fillDogsTable(user);
         checkTransferCompatibility();

}//GEN-LAST:event_fromUserListValueChanged

    private void toUserListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_toUserListMouseClicked
        // TODO add your handling code here:
}//GEN-LAST:event_toUserListMouseClicked

    private void toUserListMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_toUserListMouseReleased
        // TODO add your handling code here:
}//GEN-LAST:event_toUserListMouseReleased

    private void toUserListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_toUserListValueChanged
         User user = (User)toUserList.getSelectedValue();
         checkTransferCompatibility();
         toUserLabel.setText("<html><b>"+user.getFullName()+"</b><br/>"+
                                  user.getStreet());
}//GEN-LAST:event_toUserListValueChanged

    private void toUserListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_toUserListKeyReleased
        // TODO add your handling code here:
}//GEN-LAST:event_toUserListKeyReleased

    private void findUniteUserFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_findUniteUserFieldFocusGained
        Dogy.focusGained(findUniteUserField, findUserText);
}//GEN-LAST:event_findUniteUserFieldFocusGained

    private void findUniteUserFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_findUniteUserFieldFocusLost
        Dogy.focusLost(findUniteUserField, findUserText);
}//GEN-LAST:event_findUniteUserFieldFocusLost

    private void findUniteUserFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_findUniteUserFieldKeyPressed
        Dogy.listScroll(list, evt);
}//GEN-LAST:event_findUniteUserFieldKeyPressed

    private void findUniteUserFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_findUniteUserFieldKeyReleased
        showUserList(findUniteUserField, evt);
}//GEN-LAST:event_findUniteUserFieldKeyReleased

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        boxPopup.setVisible(false);
    }//GEN-LAST:event_formWindowClosing

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        boxPopup.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void checkTransferCompatibility()
    {
         User user = (User)toUserList.getSelectedValue();
         if(user != null)
         for(int i =0; i< dogsTable.getRowCount(); i++)
         {
             Dog dog = (Dog)dogsTable.getValueAt(i, 0);
             dogsTable.getCellEditor(i, 2).stopCellEditing();
             if(dog.getUserId() == user.getId())
             {
                 dogsTable.setValueAt(false, i, 2);
             }else
             {
                 dogsTable.setValueAt(true, i, 2);
             }
         }
    }
    
    private void fillDogsTable(User user)
    {
        try {
            DefaultTableModel model = (DefaultTableModel)dogsTable.getModel();
            model.setRowCount(0);
            ArrayList<Dog> dogs = user.getDogs();
            for(int i=0; i<dogs.size(); i++)
            {
                model.addRow(new Object[]{
                                          // transfer button enabled
                                         dogs.get(i),  // breed
                                         dogs.get(i).getBirthDate(),// birthDate
                                         false
                                         });

            }
            fromUserLabel.setText("<html><b>"+user.getFullName()+"</b><br/>"+
                                  user.getStreet());
            dogsTable.setModel(model);
        } catch (SQLException ex) {
            mainFrame.SQLException(ex);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane boxList;
    private javax.swing.JPopupMenu boxPopup;
    private javax.swing.JButton closeButton;
    private javax.swing.JTable dogsTable;
    private javax.swing.JTextField findUniteUserField;
    private javax.swing.JTextField findUserDogTransferField;
    private javax.swing.JLabel fromLabel;
    private javax.swing.JLabel fromLabel1;
    private javax.swing.JLabel fromUserLabel;
    private javax.swing.JList fromUserList;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JList list;
    private javax.swing.JLabel mainClientField;
    private javax.swing.JLabel streetField;
    private javax.swing.JLabel toUserLabel;
    private javax.swing.JList toUserList;
    private javax.swing.JButton uniteButton;
    private javax.swing.JTable uniteTable;
    private javax.swing.JTabbedPane uniteTabs;
    // End of variables declaration//GEN-END:variables


 

}
